<?php

namespace App\Services\CountProductSales;

use App\Models\Order;
use App\Models\OrderItem;
use Illuminate\Database\Eloquent\Builder;

class CountProductSales
{
	protected $order;
	
	protected $items;
	
	protected function setParmas(Order $order)
	{
		$this->order = $order;
		$this->items = $order->items;
	}
	
	protected function calculate()
	{
		foreach ($this->items as $item) {
			$product = $item->product;
			$soldCount = OrderItem::query()
				->where('product_id', $product->id)
				->whereHas('order', function (Builder $query) {
					$query->whereNotNull('paid_at');
				})->sum('amount');
			$product->update(['sold_count' => $soldCount]);
		}
	}
	
	public function count(Order $order)
	{
		$this->setParmas($order);
		$this->calculate();
	}
}
